package com.zxlspace.Chapter1.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.Future;

/**
 * @author zhangxiaolin@zhonhajt.com
 * @Title: 异步调用
 * @Package com.zxlspace.Chapter1.schedule
 * @Description:
 * @date 2018/7/12 16:39
 */
@Component
@Slf4j
public class AsyncTask {

    public static Random random = new Random();

    /**
     * @Async所修饰的函数不要定义为static类型，这样异步调用不会生效
     * @return
     * @throws Exception
     */
    @Async("taskExecutor")
    public Future<String> doTaskOne() throws Exception {
        log.info("开始做任务一");
        long startTime = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long endTime = System.currentTimeMillis();
        log.info("任务一完成，耗时:" + (endTime - startTime) + "毫秒");
        return new AsyncResult<>("任务一完成");
    }

    @Async("taskExecutor")
    public Future<String> doTaskTwo() throws Exception {
       log.info("开始做任务二");
        long startTime = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long endTime = System.currentTimeMillis();
       log.info("任务二完成，耗时:" + (endTime - startTime) + "毫秒");
        return new AsyncResult<>("任务二完成");
    }

    @Async("taskExecutor")
    public Future<String> doTaskThree() throws Exception {
       log.info("开始做任务三");
        long startTime = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long endTime = System.currentTimeMillis();
       log.info("任务三完成，耗时:" + (endTime - startTime) + "毫秒");
        return new AsyncResult<>("任务三完成");
    }
}
